package com.junxonline.plat.controller.database;

import com.junxonline.common.dao.vo.ResultVO;
import com.junxonline.common.util.CommonUtils;
import com.junxonline.plat.controller.base.BaseController;
import com.junxonline.plat.dao.vo.*;
import com.junxonline.plat.exception.ErrorCodeEnum;
import com.junxonline.plat.service.database.DatabaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author JunX
 * @ClassName: DatabaseController
 * @Description: 数据库控制器
 */

@RestController
@RequestMapping(value = "/admin/database")
public class DatabaseController extends BaseController {

    @Autowired
    private DatabaseService databaseService;
    

    /**
     * 获取数据库备份树数据
     * @return
     */
    @RequestMapping(value = "/getDatabaseTree")
    public ResultVO getDatabaseTree() {
        return getReturnSuccess(databaseService.getDatabaseTree());
    }

    /**
     * 获取当前系统数据库树数据
     * @return
     */
    @RequestMapping(value = "/getSystemDatabaseTree")
    public ResultVO getSystemDatabaseTree() {
        return getReturnSuccess(databaseService.getSystemDatabaseTree());
    }


    /**
     * 筛选查询数据库备份数据
     * @param page
     * @param vo
     * @return
     */
    @RequestMapping(value = "/queryDatabase")
    public PageResultVO queryDatabase(PageVO page, QueryDatabaseVO vo) {
        return getReturnSuccess(databaseService.queryDatabase(page, vo));
    }


    /**
     * 备份数据库
     * @param vo
     * @return
     */
    @RequestMapping(value = "/databaseBackup")
    public ResultVO databaseBackup(@RequestBody DatabaseIdsVO vo) {

        if (CommonUtils.isEmpty(vo) || CommonUtils.isEmpty(vo.getDatabaseIds())) {
            return getReturnError(ErrorCodeEnum.PARAMS_IS_NULL);
        }

        Long[] databaseIdsArray = vo.getDatabaseIds();

        Long userId = getUserId();

        boolean success = databaseService.databaseBackup(databaseIdsArray, userId);
        if (!success) {
            return getReturnError(ErrorCodeEnum.SYSTEM_ERROR);
        }

        return getReturnSuccess();

    }

    /**
     * 还原数据库
     * @param vo
     * @return
     */
    @RequestMapping(value = "/databaseRestore")
    public ResultVO databaseRestore(@RequestBody DatabaseVO vo) {
        if (CommonUtils.isEmpty(vo) || CommonUtils.isEmpty(vo.getDatabaseId())) {
            return getReturnError(ErrorCodeEnum.PARAMS_IS_NULL);
        }

        Long userId = getUserId();

        boolean success = databaseService.databaseRestore(vo, userId);
        if (!success) {
            return getReturnError(ErrorCodeEnum.SYSTEM_ERROR);
        }

        return getReturnSuccess();

    }

}
